package com.ljx.config;

import com.ljx.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author LJX
 * @Description: TODO
 * @Date: 2023/1/3 14:52
 * @Version 1.0
 */
@Configuration
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
	/**
	 * 	创建一个密码加密器,交于spring容器管理
	 */
	@Bean
	public PasswordEncoder passwordEncoder(){
		return new BCryptPasswordEncoder();
	}
	// 指定账户和密码来源
	@Autowired
	private UserService userService;
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
	}
	// 设置security认证规则

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		// 指定登录表单的规则
		http.formLogin()
				// 这个路径必须和登录表单的路径一致
				.loginProcessingUrl("/login")
				// 设置自定义登录页面
				.loginPage("/login.html")
				// 登录成功后转发的路径
				.successForwardUrl("/main")
				.permitAll();
		// 没有权限时跳转的路径
		http.exceptionHandling().accessDeniedPage("/403.html");
		//设置其他路径需要认证后才能访问
		http.authorizeRequests().anyRequest().authenticated();
		// 禁用跨站伪造请求，不适用crsf过滤器
		http.csrf().disable();
		// 设置权限不足时跳转的路径
		http.exceptionHandling().accessDeniedPage("/fail");
	}
}
